package com.example.administrator.ygddriver.welcome;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.lzy.okserver.download.DownloadListener;

import android.widget.TextView;

import com.example.administrator.ygddriver.MainActivity;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.IntoActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.DriverJoinActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.audit.AuditActivity;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;


public class WelcomeActivity extends BaseActivity {
    private CountDownTimer timer;
    private TextView mTimeTv;

    @Override
    public int initLayout() {
        return R.layout.activity_welcome;
    }

    @Override
    public void initView() {
        mTimeTv = findViewById(R.id.activity_welcome_time_tv);
    }

    @Override
    public void initDate() {
        requestCemera();
        startTime();
    }

    private void requestCemera() {
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
                initAppVersionHtml();
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
                initAppVersionHtml();
            }
        }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE});
    }

    private void setAccessToken() {
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                if (TextUtils.isEmpty(data.getC_id()) || TextUtils.isEmpty(data.getC_token())) {
                    Intent intent = new Intent(WelcomeActivity.this, IntoActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    initAccessTokenHtml(data.getC_id(), data.getC_token());
                }

            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {
                Intent intent = new Intent(WelcomeActivity.this, IntoActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void startTime() {
        timer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeTv.setText((millisUntilFinished / 1000) + "s跳过");
            }

            @Override
            public void onFinish() {
                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        };


    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    //获取token 验证
    private void initAccessTokenHtml(String c_id, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_id", c_id);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", UrlValuse.TYPE);
        hashMap.put("c_registrationid", JPushInterface.getRegistrationID(this));
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.ACCESS_TOKEN, hashMap, AccessTokenRequestBean.class, new OkGoRequests.OnTrue<AccessTokenRequestBean>() {
            @Override
            public void hasData(AccessTokenRequestBean date) {
                if (date.isSuccess()) {
                    if (date.getResult().getC_status().equals("3") || date.getResult().getC_status().equals("1")) {
                        Intent intent = new Intent(WelcomeActivity.this, AuditActivity.class);
                        intent.putExtra("status", date.getResult().getC_status());
                        intent.putExtra("c_drivertype", date.getResult().getC_drivertype());
                        startActivity(intent);
                        finish();
                    } else if (date.getResult().getC_status().equals("0")) {
                        Intent intent = new Intent(WelcomeActivity.this, DriverJoinActivity.class);
                        startActivity(intent);
                        finish();

                    } else if (date.getResult().getC_status().equals("2")) {
                        timer.start();
                    }

                } else {
                    Intent intent = new Intent(WelcomeActivity.this, IntoActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }, new OkGoRequests.OnError<AccessTokenRequestBean>() {
            @Override
            public void noData() {

            }
        });


    }

    private void initUpdaloadDialog(final String downloadUrl) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.logo_1). // 设置提示框的图标
                setMessage("发现新版本！请及时更新").// 设置要显示的信息
                setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                initUpVersion(downloadUrl);//下载最新的版本程序
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });//设置取消按钮,null是什么都不做，并关闭对话框
        AlertDialog alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
    }

    //检查更新
    private void initAppVersionHtml() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_type", UrlValuse.TYPE);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.APP_VERSION, hashMap, AppVersionRequestBean.class, new OkGoRequests.OnTrue<AppVersionRequestBean>() {
            @Override
            public void hasData(AppVersionRequestBean date) {
                if (date.isSuccess()) {
                    if (UrlValuse.VERSION.equals(date.getResult().getC_version())) {
                        setAccessToken();
                    } else {
                        initUpdaloadDialog(date.getResult().getC_url());
                    }

                }
            }
        }, new OkGoRequests.OnError<AppVersionRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    private void initUpVersion(String downloadUrl) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("正在下载新版本");
        progressDialog.setCancelable(false);//不能手动取消下载进度对话框
        progressDialog.setMax(100);
        progressDialog.show();
        String s = String.valueOf(Environment.getExternalStorageDirectory());

        GetRequest<File> request = OkGo.get(downloadUrl);
        DownloadTask task = OkDownload.request("tag", request).folder(s + "/YGDDriver/apk/").fileName(UrlValuse.VERSION + ".apk").save().register(new DownloadListener("tag") {
            @Override
            public void onStart(Progress progress) {

            }

            @Override
            public void onProgress(Progress progress) {
                progressDialog.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Progress progress) {

            }

            @Override
            public void onFinish(File file, Progress progress) {
                checkOreo(file);
                progressDialog.dismiss();
            }

            @Override
            public void onRemove(Progress progress) {

            }
        });
        task.start();
    }

    /**
     * 检测版本8.0
     */
    public void checkOreo(File file) {
        boolean installAllowed;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            installAllowed = getPackageManager().canRequestPackageInstalls();
            if (installAllowed) {
                installApk(file);
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                installApk(file);
                return;
            }
        } else {
            installApk(file);
        }
    }

    //安装apk，兼容7.0
    protected void installApk(File file) {
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址和清单文件中保持一致   参数3 共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.example.administrator.ygddriver.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivity(intent);
        finish();
    }
}
